package com.travel.rabbit.utils;

import com.travel.rabbit.service.DistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: luoxian
 * @Date: 2020/6/9 14:17
 * @Email: 15290810931@163.com
 */
@Slf4j
@Component
public class IdCardUtil {

    @Resource
    DistrictService districtService;

    /**
     * 根据身份证的号码算出当前身份证持有者的性别和年龄 18位身份证
     *
     * @return
     * @throws Exception
     */
    public Map<String, String> getCarInfo(String cardCode) {
        Map<String, String> map = new HashMap<String, String>(16);

        String year = cardCode.substring(6).substring(0, 4);
        String month = cardCode.substring(10).substring(0, 2);
        String day= cardCode.substring(12).substring(0,2);
        log.info("根据身份证得到年月日:{}",year,month,day);

        String birthday = year.concat( "-" ).concat( month ).concat( "-" ).concat( day);
        String sex;
        // 判断性别
        if (Integer.parseInt(cardCode.substring(16).substring(0, 1)) % 2 == 0) {
            //女
            sex = "1";
        } else {
            //男
            sex = "0";
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentYear  = format.format(date).substring(0, 4);
        String currentMonth = format.format(date).substring(5, 7);
        String currentDay   =format.format(date).substring(8,10);
        int age = 0;
        // 当前月份大于用户出身的月份表示已过生
        if (Integer.parseInt(month) <= Integer.parseInt(currentMonth)) {
            age = Integer.parseInt(currentYear) - Integer.parseInt(year) + 1;
        } else {
            // 当前用户还没过生
            age = Integer.parseInt(currentMonth) - Integer.parseInt(year);
        }
        String address = getNativePlace(cardCode);
        map.put("address",address);
        map.put( "birthday", birthday);
        map.put("gender", sex);
        map.put("age", String.valueOf( age ));
        return map;
    }

    public String getNativePlace(String idCard) {
        int nativePlaceCode = Integer.parseInt(idCard.substring(0,6));
        String provinceCode = String.valueOf(nativePlaceCode / 10000);
        String cityCode = String.valueOf(nativePlaceCode / 100);
        String areaCode = String.valueOf(nativePlaceCode);
        String province =  districtService.queryNameById(provinceCode);
        String city     =  districtService.queryNameById(cityCode);
        String area     =  districtService.queryNameById(areaCode);
        String nativePlace = "";
        if (province != null) {
            nativePlace += province;
        }
        if (city != null) {
            nativePlace += city;
        }
        if (area != null) {
            nativePlace += area;
        }
        return nativePlace;
    }
}
